<template>
  <div>
    <!-- 城市列表头部 -->
    <van-nav-bar title="城市列表" left-arrow @click-left="onClickLeft" fixed />
    <div class="mianBody">
      <!-- <div class="currentCity">当前城市</div> -->
      <!-- 城市列表 -->
      <div class="listBox">
        <van-index-bar :index-list="CityIndex" :sticky="false">
          <div v-for="(val, key) in CityList" :key="key">
            <van-index-anchor :index="key" />
            <van-cell
              :title="item.label"
              v-for="item in val"
              :key="item.value"
              @click="selCityFn(item)"
            >
            </van-cell>
          </div>
        </van-index-bar>
      </div>
    </div>
  </div>
</template>

<script>
import { cityListApis, cityHotApis } from "@/api/area";
export default {
  name: "city-page",
  data() {
    return {
      CityList: [],
      CityIndex: [],
      CityHot: {},
    };
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    // 1.渲染城市列表的数据格式为：
    // {a:[{},{}],b:[{},{}]}
    // 渲染右侧索引的数据格式
    // ['a','b']
    formData(list) {
      list.sort((a, b) =>
        a.short.toUpperCase() > b.short.toUpperCase() ? 1 : -1
      );
      list.forEach((item) => {
        // 1.遍历数组 拿到第一个城市的首字母
        const first = item.short.substr(0, 1).toUpperCase();
        // 2.判断cityList中是否有该分类
        if (this.CityList[first]) {
          // 3.如果这个对象有分类直接push
          // CityList[first]=>[{},{}]
          this.CityList[first].push(item);
        } else {
          // 如果没有，就先创建一个数组，把当前城市信息添加到数组中
          this.CityList[first] = [item];
        }
      });
      this.CityIndex = Object.keys(this.CityList).sort();
      this.CityIndex.unshift("#", "热");
    },
    selCityFn(item) {
      localStorage.setItem("sel_city", JSON.stringify(item));
      if (localStorage.getItem("list")) {
        this.$router.push("/home/list");
        localStorage.removeItem("list");
      } else {
        this.$router.push("/home");
      }
    },
  },
  async created() {
    const res = await cityListApis({ level: 1 });
    this.formData(res.body);
    // 2.获取热门城市数据
    // 将数据添加到CityList中//属性名：属性值
    // 将索引添加到CityIndex中
    const hot = await cityHotApis();
    this.CityHot["当前城市"] = [
      JSON.parse(localStorage.getItem("sel_city")) || {
        label: "上海",
        value: "",
      },
    ];
    this.CityHot["热门城市"] = hot.body;
    this.CityList = { ...this.CityHot, ...this.CityList };
  },
};
</script>

<style scoped lang="less">
.van-nav-bar {
  background-color: #1cb676;
}
/deep/.van-nav-bar .van-icon {
  color: #fff;
}
/deep/.van-ellipsis {
  font-size: 18px;
  color: #fff;
}
.mianBody {
  padding-top: 45px;
}
.currentCity {
  color: #999999;
  font-size: 14px;
  padding: 10px 15px;
}
</style>
